package com.abc.robot01.activity

import android.os.Bundle
import android.os.RemoteException
import android.util.Log
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.vivemodel.AddQAViewModel2
import com.ainirobot.coreservice.client.Definition
import com.ainirobot.coreservice.client.RobotApi
import com.ainirobot.coreservice.client.listener.ActionListener
import com.ainirobot.coreservice.client.listener.CommandListener
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray

/**
 * 导览界面
 */
class Nav01Activity : BaseVoiceActivity() {
    private val viewModel: AddQAViewModel2 by viewModels()

    val receptionPointMap = mapOf(
        "门厅" to ReceptionPointContent(
            welcomeMessage = listOf("尊贵的VIP客户，我是您的专属小二，接下来将由我带您逛一下我这200多平的大豪斯哦！"),
            guideMessage = "我家今年年中刚从厦门搬到深圳，主要包含研发中心、营销中心、会议室、财务室、茶室、总经理室6个区域"
        ),
        "机房" to ReceptionPointContent(
            welcomeMessage = listOf("哎呀，机房重地放了很多机器和设备，太热啦，溜啦溜啦~"),
            guideMessage = "走，我带你们去我们的武器库也就是机房重地看看"
        ),
        "行政办公室" to ReceptionPointContent(
            welcomeMessage = listOf("小姐姐在专心工作，不要去打扰她"),
            guideMessage = "现在我们去看看漂亮的人事小姐姐去"
        ),
        "营销中心" to ReceptionPointContent(
            welcomeMessage = listOf("营销中心主要包括市场部、业务部、设计商学院...偷偷告诉你，营销中心美女可多啦！",
                "我们去年得到了央妈报道，在央视大型纪录片栏目《溯源》中播出"),
            guideMessage = "前方即将到达我们的参谋部，也就是营销中心啦！"
        ),
        "研发中心" to ReceptionPointContent(
            welcomeMessage = listOf("这里就是我的研发爸爸所在的区域了，也就是研发中心啦！哦对了，我最喜欢的兰兰姐也在这儿！"),
            guideMessage = "现在我带你去找我爸！"
        ),
        "接待室" to ReceptionPointContent(
            welcomeMessage = listOf("来喝点茶歇歇吗？虽然我不是茶艺大师，但是我可以叫我爸过来沏茶。要不一会儿我们再来这歇歇！"),
            guideMessage = "逛累了吗？我们去休息一下吧~"
        ),
        "会议室" to ReceptionPointContent(
            welcomeMessage = listOf("会议室到了，这里你能见到我的好兄弟，也就是靠窗那边扑克脸的那位“电脑投屏”，我们兄弟俩一起闯江湖，约定好了不离不弃~"),
            guideMessage = "我有一个秘密要告诉你，跟我来！"
        ),
        "总经理室" to ReceptionPointContent(
            welcomeMessage = listOf("BOSS云集，快撤~"),
            guideMessage = "前方高能，即将到达作战指挥部，非战斗人员快速撤离！"
        ),
        "电梯接待点" to ReceptionPointContent(
            welcomeMessage = listOf("欢迎光临，你看我如此可爱，要不跟我走吧~"),
            guideMessage = ""
        ),
        "大门接待点" to ReceptionPointContent(
            welcomeMessage = listOf("欢迎莅临广东省一束光软件技术有限公司，请问尊贵的客人，我有这个荣幸可以带你转一转吗？"),
            guideMessage = ""
        )
    )

private val  actionListener = object:ActionListener(){
    override fun onError(errorCode: Int, errorString: String?, extraData: String?) {
        super.onError(errorCode, errorString, extraData)
        job?.cancel()
        playTTS("导航失败")
        lifecycleScope.launch {
            delay(3000)
            current += 1
            if(current==viewModel.customerList.value.size) {
                current=0
            }
            goto(viewModel.customerList.value.get(current).name)
        }
        Log.e(TAG, "onError: errorCode:$errorCode, errorString:$errorString");
    }

    @Throws(RemoteException::class)
    override fun onResult(status: Int, response: String) {
        Log.e(TAG, "onResult: $status, $response");
        when (status) {
            Definition.RESULT_OK -> if ("true" == response) {
                Log.e(TAG,"导航成功："+  viewModel.customerList.value.get(current).name);
                val  tts = receptionPointMap.get(viewModel.customerList.value.get(current).name)
                if(tts!=null) {
                    playTTS(tts.welcomeMessage.random())
                }
                lifecycleScope.launch {
                    delay(5000)
                    current += 1
                if(current==viewModel.customerList.value.size) {
                    current=0
                }
                    goto(viewModel.customerList.value.get(current).name)
                }
            } else {
                playTTS("导航失败")
            }
            Definition.ACTION_RESPONSE_STOP_SUCCESS -> {}
        }
    }
}
    private var job: Job? = null
    fun goto(pos:String){
        Log.e(TAG, "现在去$pos");
//        playTTS("现在去$pos，咔嚓咔嚓，机器人出动！前方注意，让路哟")
//        playTTS("现在去$pos，各位注意，我是个有导航任务的小可爱，请给我留条小道吧")
        RobotApi.getInstance().startNavigation(0, pos, 0.2, 30*1000,actionListener
        )
        job?.cancel()
       job = lifecycleScope.launch {
//           delay(10000)
//           while(true){
               delay(1000)
               playTTS(  receptionPointMap.get(pos)!!.guideMessage)
//           }
        }

    }
    var  current = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate");
        lifecycleScope.launch {
            delay(2000)
            RobotApi.getInstance().getPlaceList(0, object : CommandListener() {
                override fun onResult(result: Int, message: String?, extraData: String?) {
                    Log.e(TAG, "JSONArray:"+message);
                    val jsonArray = JSONArray(message!!)
                    val  s = mutableListOf<Place>()
                    for (i in 0 until jsonArray.length()) {
                        val jsonObject = jsonArray.getJSONObject(i)
                        val place = Place(
                            id = jsonObject.getString("id"),
                            ignoreDistance = jsonObject.getBoolean("ignoreDistance"),
                            name = jsonObject.getString("name"),
                            obsDistance = jsonObject.getDouble("obsDistance"),
                            postype = jsonObject.getInt("postype"),
                            safeDistance = jsonObject.getInt("safeDistance"),
                            status = jsonObject.getInt("status"),
                            theta = jsonObject.getDouble("theta"),
                            x = jsonObject.getDouble("x"),
                            y = jsonObject.getDouble("y"),
                            messageType = jsonObject.getInt("messageType"),
                            time = jsonObject.getLong("time")
                        )
                        Log.e(TAG, "JSONArray:"+place.name);
                        if(place.name=="回充点") continue
                        if(place.name=="接待点") continue
//                        if(place.name=="闸机入口") continue
                        if(place.name=="充电桩") continue
                        s.add(place)
                    }
                    viewModel._customerList.value = s
                    current = 0
                    goto(viewModel.customerList.value[current].name)
                }
            })
//            delay(1000)

        }
        setContent {
            Column {
                List()
                MyButton01(text = "结束导览",containerColor= Color.Blue,textColor= Color.White){
                    RobotApi.getInstance().stopNavigation(0)
                }
            }
        }
    }

    @Composable
    fun List(){
        val list by viewModel.customerList.collectAsState()
        list.forEachIndexed { index,it ->
            MyButton01(text = "${it.name}",containerColor= Color.Blue,textColor= Color.White){ it2->
               current= index
                goto("${it.name}")
            }
        }
    }
    companion object {
        val TAG = "导览"
    }
}

// 定义数据类来表示 JSON 对象
data class Place(
    val id: String,
    val ignoreDistance: Boolean,
    val name: String,
    val obsDistance: Double,
    val postype: Int,
    val safeDistance: Int,
    val status: Int,
    val theta: Double,
    val x: Double,
    val y: Double,
    val messageType: Int,
    val time: Long
)


data class ReceptionPointContent(
    val welcomeMessage: List<String>, // 接待点话语
    val guideMessage: String    // 导览串词
)
